//
//  ReportViewController.m
//  Riese
//
//  Created by air on 2019/10/26.
//  Copyright © 2019 wangjinyu. All rights reserved.
//

#import "ReportViewController.h"
#import "HeartLive.h"
#import <MLMenu/MLMenuView.h>

#import "UIScrollView+Snapshot.h"
#import <Photos/PHPhotoLibrary.h>
#import <Photos/PHAssetChangeRequest.h>

#import "AppDelegate.h"
#import "JHRotatoUtil.h"

@interface ReportViewController () {
    float xCoordinateInMoniter;
    double ybase;
    MLMenuView *menuView;
    UIInterfaceOrientation   _lastOrientation;
}

@property (nonatomic, strong) UIScrollView *scroll;
@property (nonatomic, strong) UIView *whiteView1;
@property (nonatomic, strong) UILabel *resultLabel;
@property (nonatomic, strong) UIView *resultBorder;
@property (nonatomic, strong) UIView *blackBorder;

@property (nonatomic , strong) NSArray *dataSource;

@property (nonatomic , strong) HeartLive *refreshMoniterView;

@property (nonatomic, assign) NSInteger number;
@property (nonatomic, assign) NSInteger row; // 折线图第几行
@property (nonatomic, assign) NSInteger lineY; // 每一行线起点

@property (nonatomic, strong) PointContainer *container;

@end

@implementation ReportViewController

- (HeartLive *)refreshMoniterView
{
    if (!_refreshMoniterView) {
        CGFloat w = (NSInteger)((SCREEN_WIDTH - 30)/30) * 30 + 2;
        CGFloat xOffset = (SCREEN_WIDTH - 30 - w)/2;
        _refreshMoniterView = [[HeartLive alloc] initWithFrame:CGRectMake(xOffset, 122, w, 600)];
        _refreshMoniterView.backgroundColor = [UIColor whiteColor];
    }
    return _refreshMoniterView;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.container clear];
    
    if (self.isRight) {
        [JHRotatoUtil forceOrientation:UIInterfaceOrientationLandscapeRight];
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.Rotate = 1;
    }
    else {
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.Rotate = 0;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.container clear];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = NSLocalizedString(@"Report", nil);
    
    xCoordinateInMoniter = 0;
    ybase = 90;
    [self.container clear];
    self.container = [PointContainer sharedContainer];
    
    self.number = 0;
    self.row = 0;
    
    [self makeNav];
    [self makeUI];

    self.view.backgroundColor = kColor(243, 243, 243);
    
    void (^createData)(void) = ^{
        NSMutableArray * dataArray = [NSMutableArray array];
        NSArray *arr = self.dataDic[@"data"];
        for (int i = 0; i < arr.count; i++) {
            [dataArray addObject:arr[i]];
        }
        
        self.dataSource = dataArray;
        [self timerRefresnFun];
    };
    createData();
}

- (void)makeNav {
    UIButton *downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    downloadBtn.frame = CGRectMake(0, 0, kNavHeight, kNavHeight);
    [downloadBtn setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
    [downloadBtn addTarget:self action:@selector(downloadBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:downloadBtn];
}

- (void)makeUI {
    if ([self.isRight isEqualToString:@"1"]) {
        self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kNavHeight)];
    }
    else {
        self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kNavBarAndStatusBarHeight - kBottomSafeHeight)];
    }
    self.scroll.backgroundColor = [UIColor clearColor];
    self.scroll.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scroll];
    
    self.whiteView1 = [[UIView alloc] initWithFrame:CGRectMake(15, 20, SCREEN_WIDTH - 30, 215 + self.refreshMoniterView.height)];
    self.whiteView1.backgroundColor = [UIColor whiteColor];
    self.whiteView1.layer.cornerRadius = 4;
    self.whiteView1.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.2].CGColor;
    self.whiteView1.layer.shadowOffset = CGSizeMake(0,0);
    self.whiteView1.layer.shadowOpacity = 1;
    self.whiteView1.layer.shadowRadius = 7;
    [self.scroll addSubview:self.whiteView1];
    
    self.resultLabel = [[UILabel alloc] init];
    self.resultLabel.text = [NSString stringWithFormat:@"%@ : %@", NSLocalizedString(@"Result", nil), self.result];
    self.resultLabel.textColor = kColor(102, 102, 102);
    self.resultLabel.font = kRegularFont(14);
    [self.whiteView1 addSubview:self.resultLabel];
    
    self.resultBorder = [UIView new];
    self.resultBorder.backgroundColor = [UIColor clearColor];
    self.resultBorder.layer.borderWidth = 1;
    self.resultBorder.layer.borderColor = kColor(255, 204, 205).CGColor;
    [self.whiteView1 addSubview:self.resultBorder];
    
    [self.whiteView1 addSubview:self.refreshMoniterView];
    [self makeView1];
}

- (void)makeView1 {
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = NSLocalizedString(@"ECG Report", nil);
    titleLabel.textColor = kColor(51, 51, 51);
    titleLabel.font = kRegularFont(15);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.whiteView1 addSubview:titleLabel];
    
    UIImageView *logo = [UIImageView new];
    logo.image = [UIImage imageNamed:@"logo_report"];
    [self.whiteView1 addSubview:logo];
    
    self.blackBorder = [UIView new];
    self.blackBorder.backgroundColor = [UIColor clearColor];
    self.blackBorder.layer.borderWidth = 1;
    self.blackBorder.layer.borderColor = kColor(102, 102, 102).CGColor;
    [self.whiteView1 addSubview:self.blackBorder];
    
    UILabel *nameLabel = [UILabel new];
    nameLabel.text = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"Nickname", nil), defaults(@"nickname")];
    nameLabel.textColor = kColor(51, 51, 51);
    nameLabel.font = kRegularFont(12);
    [self.blackBorder addSubview:nameLabel];
    
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy"];
    NSString *year=[dateformatter stringFromDate:senddate];
    
    NSString *sex = [defaults(@"sex") isEqual:@"0"] ? NSLocalizedString(@"Male", nil) : NSLocalizedString(@"Female", nil);
    NSString *age = [NSString stringWithFormat:@"%ld", year.integerValue - [defaults(@"age") integerValue]];
    
    UILabel *sexLabel = [UILabel new];
    sexLabel.text = [NSString stringWithFormat:@"%@: %@      %@: %@", NSLocalizedString(@"Sex", nil), sex, NSLocalizedString(@"Age", nil), age];
    sexLabel.textColor = kColor(51, 51, 51);
    sexLabel.font = kRegularFont(12);
    sexLabel.textAlignment = NSTextAlignmentRight;
    [self.blackBorder addSubview:sexLabel];
    
    NSInteger duration = [self.dataDic[@"TimeLen"] integerValue]/250;
    UILabel *hrLabel = [UILabel new];
    
    NSString *year1 = self.dataDic[@"year"];
    NSString *month1 = [Common turnString:self.dataDic[@"month"]];
    NSString *day1 = [Common turnString:self.dataDic[@"day"]];
    NSString *hour1 = [Common turnString:self.dataDic[@"hour"]];
    NSString *min1 = [Common turnString:self.dataDic[@"min"]];
    NSString *sec1 = [Common turnString:self.dataDic[@"sec"]];
    
    hrLabel.text = [NSString stringWithFormat:@"%@ : %@bmp   %@ : %lds   %@ : %@/%@/%@ %@:%@:%@", NSLocalizedString(@"HR", nil), self.dataDic[@"HeartRate"], NSLocalizedString(@"Duration", nil), duration, NSLocalizedString(@"Time", nil), month1, day1, year1, hour1, min1, sec1];
    hrLabel.textColor = kColor(51, 51, 51);
    hrLabel.font = kRegularFont(12);
    hrLabel.adjustsFontSizeToFitWidth = YES;
    [self.blackBorder addSubview:hrLabel];
    
    UILabel *gainLabel = [UILabel new];
    gainLabel.text = [NSString stringWithFormat:@"%@ : %@    %@ : %@", NSLocalizedString(@"Gain", nil), self.gainStr, NSLocalizedString(@"Speed", nil), self.speedStr];
    gainLabel.textColor = kColor(102, 102, 102);
    gainLabel.font = kRegularFont(12);
    gainLabel.textAlignment = NSTextAlignmentCenter;
    [self.refreshMoniterView addSubview:gainLabel];
    
    // layout
    titleLabel.sd_layout.leftSpaceToView(self.whiteView1, 15).rightSpaceToView(self.whiteView1, 15).topSpaceToView(self.whiteView1, 25).heightIs(21);
    logo.sd_layout.rightSpaceToView(self.whiteView1, 10).topSpaceToView(self.whiteView1, 10).widthIs(70).heightIs(19);
    
    CGFloat w = (NSInteger)((SCREEN_WIDTH - 30)/30) * 30 + 2;
    CGFloat xOffset = (SCREEN_WIDTH - 30 - w)/2;
    
    self.blackBorder.sd_layout.leftSpaceToView(self.whiteView1, xOffset + 0.5).rightSpaceToView(self.whiteView1, xOffset + 0.5).topSpaceToView(self.whiteView1, 51).heightIs(71);
    
    sexLabel.sd_layout.rightSpaceToView(self.blackBorder, 12).topSpaceToView(self.blackBorder, 12).heightIs(16);
    [sexLabel setSingleLineAutoResizeWithMaxWidth:0];
    nameLabel.sd_layout.leftSpaceToView(self.blackBorder, 12).rightSpaceToView(sexLabel, 12).topSpaceToView(self.blackBorder, 12).heightIs(16);
    hrLabel.sd_layout.leftSpaceToView(self.blackBorder, 12).rightSpaceToView(self.blackBorder, 12).topSpaceToView(nameLabel, 15).heightIs(16);
    
    gainLabel.sd_layout.leftSpaceToView(self.refreshMoniterView, 0).rightSpaceToView(self.refreshMoniterView, 0).topSpaceToView(self.refreshMoniterView, 10).heightIs(20);
}

- (void)downloadBtnClick {
    NSArray *titles = @[NSLocalizedString(@"Save as Image", nil), NSLocalizedString(@"Send in PDF", nil), NSLocalizedString(@"Printer", nil)];
    
    __weak ReportViewController *weakself = self;
    if ([self.isRight isEqualToString:@"1"]) {
        menuView = [[MLMenuView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 140 - 10, 0, 140, 122) WithTitles:titles WithImageNames:nil WithMenuViewOffsetTop:kNavHeight + 8];
    }
    else {
        menuView = [[MLMenuView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 140 - 10, 0, 140, 122) WithTitles:titles WithImageNames:nil WithMenuViewOffsetTop:kNavBarAndStatusBarHeight + 8];
    }
    [menuView setMenuViewBackgroundColor:kColor(34, 163, 250)];
//    [menuView setCoverViewBackgroundColor:[UIColor colorWithWhite:0 alpha:0.2]];
    menuView.separatorOffSet = 5;
    menuView.separatorColor = kColor(31, 152, 234);
    menuView.titleColor = [UIColor whiteColor];
    menuView.font = kRegularFont(14);
    menuView.didSelectBlock = ^(NSInteger index) {
        if (index == 0) {
            // save as image
            [weakself saveImage];
        }
        else if (index == 1) {
            // send in pdf
            [weakself shareImageWithPDF];
        }
        else {
            // printer
            [weakself shareImage];
        }
    };
    [menuView showMenuEnterAnimation:MLAnimationStyleTop];
}

#pragma mark - share Image
- (void)saveImage {
    UIImage *img = [self snapshotScreenInView:self.whiteView1];
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(completedWithImage:error:context:), NULL);
}


#pragma mark  -----截取屏幕指定区域view-----
- (UIImage *)snapshotScreenInView:(UIView *)contentView{
    
    CGSize size = contentView.bounds.size;
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDTH, size.height), NO, [UIScreen mainScreen].scale);
    CGRect rect = CGRectMake(0, 0, SCREEN_WIDTH, size.height);
    
    //  自iOS7开始，UIView类提供了一个方法-drawViewHierarchyInRect:afterScreenUpdates: 它允许你截取一个UIView或者其子类中的内容，并且以位图的形式（bitmap）保存到UIImage中
    [contentView drawViewHierarchyInRect:rect afterScreenUpdates:YES];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

- (void)completedWithImage:(UIImage *)image error:(NSError *)error context:(void *)contextInfo{
    if (!image || error) {
        [YJProgressHUD showMessage:NSLocalizedString(@"Save failed", nil) inView:self.view];
    }
    else {
        [YJProgressHUD showMessage:NSLocalizedString(@"Save successfully", nil) inView:self.view];
    }
}

- (void)shareImageWithPDF {
    UIImage *img = [self snapshotScreenInView:self.whiteView1];
    NSArray *arr = @[img];
    NSString * path = [self createPDF:arr];
    
    NSURL *  file = [NSURL fileURLWithPath:path];
    NSData * data = [NSData dataWithContentsOfFile:path];
    
//    UIImage *img = [self snapshotScreenInView:self.whiteView1];
//    NSData * data = UIImagePNGRepresentation(img);
    NSArray *activityItems = @[file];//@[data];
    UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    activityVc.modalPresentationStyle = 0;
    [self presentViewController:activityVc animated:YES completion:nil];
    activityVc.completionWithItemsHandler = ^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"分享成功");
        }else{
            NSLog(@"分享取消");
        }
    };
}

- (void)shareImage {
    UIImage *img = [self snapshotScreenInView:self.whiteView1];
    NSData * data = UIImagePNGRepresentation(img);
    NSArray *activityItems = @[data];
    UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    activityVc.modalPresentationStyle = 0;
    [self presentViewController:activityVc animated:YES completion:nil];
    activityVc.completionWithItemsHandler = ^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"分享成功");
        }else{
            NSLog(@"分享取消");
        }
    };
}

-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
    NSLog(@"json解析失败：%@",err);
    return nil;
    }
    return dic;
}

#pragma mark - 哟
//刷新方式绘制
- (void)timerRefresnFun {
    for (int i = 0; i < self.dataSource.count; i++) {
        [self.container addPointAsRefreshChangeform:[self bubbleRefreshPoint]];
    }
    
    CGFloat w = (NSInteger)((SCREEN_WIDTH - 30)/30) * 30 + 2;
    CGFloat xOffset = (SCREEN_WIDTH - 30 - w)/2;
    self.refreshMoniterView.frame = CGRectMake(xOffset, 122, w, 60 * (self.row + 2) + 30 + 2);

    self.resultBorder.frame = CGRectMake(xOffset + 0.5, 120 + self.refreshMoniterView.height, SCREEN_WIDTH - 30 - (xOffset + 0.5) * 2, 64);
    self.resultLabel.frame = CGRectMake(15, 132 + self.refreshMoniterView.height, SCREEN_WIDTH - 30 - 30, 20);
    self.whiteView1.frame = CGRectMake(15, 20, SCREEN_WIDTH - 30, self.refreshMoniterView.height + 215);
    self.scroll.contentSize = CGSizeMake(0, self.whiteView1.height + 40);
    
    [self.refreshMoniterView fireDrawingWithPoints:self.container.refreshPointContainer pointsCount:self.container.numberOfRefreshElements];
}

#pragma mark - DataSource
- (CGPoint)bubbleRefreshPoint
{
    static NSInteger dataSourceCounterIndex = -1;
    dataSourceCounterIndex ++;
    dataSourceCounterIndex %= [self.dataSource count];
    
    CGFloat y = ybase - ([self.dataSource[dataSourceCounterIndex] doubleValue] - 16384) * self.gain * self.n;
    CGPoint targetPointToAdd = (CGPoint){xCoordinateInMoniter,y};
    xCoordinateInMoniter += self.pixelPerPoint;
    if (xCoordinateInMoniter >= (int)(CGRectGetWidth(self.refreshMoniterView.frame))) {
        xCoordinateInMoniter = 0;
        ybase += 60;
        self.row++;
    }

    return targetPointToAdd;
}


#pragma mark - 创建PDF储存路径
- (NSString *)createPDFPathWithName:(NSString *)pdfName {
    NSFileManager * fileManager = [NSFileManager defaultManager];

    NSString * finderPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                                                                  NSUserDomainMask, YES) lastObject]
                             stringByAppendingPathComponent:@"PDF"];
    
    if (![fileManager fileExistsAtPath:finderPath])
    {
        [fileManager createDirectoryAtPath:finderPath withIntermediateDirectories:YES
                                attributes:nil
                                     error:NULL];
    }
    return [finderPath stringByAppendingPathComponent:pdfName];
}

#pragma mark - 创建PDF
- (NSString *)createPDF:(NSArray *)imageArr {
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld.pdf", (long)([datenow timeIntervalSince1970]*1000)];
    NSString * pdfPath = [self createPDFPathWithName:timeSp];
 
    // CGRectZero 表示默认尺寸，参数可修改，设置自己需要的尺寸
    UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, NULL);
    
    CGRect  pdfBounds = UIGraphicsGetPDFContextBounds();
    CGFloat pdfWidth  = pdfBounds.size.width;
    CGFloat pdfHeight = pdfBounds.size.height;
    
    [imageArr enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) {
        // 绘制PDF
        UIGraphicsBeginPDFPage();
        
        CGFloat imageW = image.size.width;
        CGFloat imageH = image.size.height;
        
        if (imageW <= pdfWidth && imageH <= pdfHeight)
        {
            CGFloat originX = (pdfWidth - imageW) / 2;
            CGFloat originY = (pdfHeight - imageH) / 2;
            [image drawInRect:CGRectMake(originX, originY, imageW, imageH)];
        }
        else
        {
            CGFloat width,height;

            if ((imageW / imageH) > (pdfWidth / pdfHeight))
            {
                width  = pdfWidth;
                height = width * imageH / imageW;
            }
            else
            {
                height = pdfHeight;
                width = height * imageW / imageH;
            }
            [image drawInRect:CGRectMake((pdfWidth - width) / 2, (pdfHeight - height) / 2, width, height)];
        }
    }];
    
    UIGraphicsEndPDFContext();

    return pdfPath;
}
@end
